<?php
/**
 * This class represents a single radio button element. It can contain other elements. If this element
 * is not selected when the validation is run, the children elements will not be validated.
 *
 * @author Niels Janssen
 * @since 2008-08-02
 * @package Form.Containers
 */
class RadioButton extends FormContainer {

	private $selected = false;
	private $disable = false;
	private $groupName = '';
	/**
	 * Sets the value of this radio button
	 *
	 * @param String $value
	 */
	function __construct( $value, $label ) {
		$this->value = $value;
		$this->name	 = $value;
		$this->setProperties ( array ( 'label' => $label ) );
	}

	/**
	 * Sets the name of this radio button, called by the RadioButtonContainer.
	 *
	 * @param String $name
	 */
	public function setName( $name ) {
		$this->groupName = $name;
	}

	/**
	 * Sets wheter or not this radiobutton is selected or not, called by the RadioButtonContainer.
	 *
	 * @param boolean $selected
	 */
	public function setSelected( $selected ) {
		$this->selected = $selected;
		$this->parent->setSelected( $this );
	}

	/**
	 * Gets the value of this element.
	 *
	 * @return String
	 */
	public function getValue( ) {
		return $this->value;
	}

	/**
	 * Sets the parent of this element, overridden method.
	 *
	 * @param RadioButtonContainer $container
	 * @see FormNode::isValid()
	 */
	public function setParent( RadioButtonContainer $container ) {
		parent::setParent( $container );
	}

	/**
	 * Checks the validity of this element, overridden method.
	 *
	 * @return boolean
	 * @see FormNode::isValid()
	 */
	public function isValid() {
		return $this->selected ? parent::isValid() : true;
	}
	
	public function setDisabled( $disable ) {
		$this->disable = $disable;
	}

	/**
	 *
	 * @see FormNode::__toString()
	 */
	public  function __toString() {
		$output = '
			<div class="radiobutton" id="radiobuttondiv_' . $this->groupName . '_' . $this->value . '">
				<label><input type="radio" ' . ( $this->disable ? 'disabled="disabled"' : '' ) . ' name="' . ( $this->getFormName() != '' ? $this->getFormName() . '_' : '' ) . $this->groupName . '" value="' . $this->value . '" ' . ( $this->selected ? 'checked="checked"' : '' ) . ' />' . $this->getProperty ( 'label' ) . '</label>';

		if( $this->hasChildren() ) {
			$output .= '<div class="radioelements" id="radioelements_' . $this->groupName . '_' . $this->value . '">';

			foreach( $this->children as $child ) {
				$output .= $child;
			}

			$output .= '</div>';
		}

		$output .= '
			</div>';

		return $output;
	}
}